package com.dkd.manage.controller;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.core.page.TableDataInfo;
import com.dkd.common.enums.BusinessType;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.manage.domain.TbChannel;
import com.dkd.manage.domain.TbEmp;
import com.dkd.manage.domain.TbSku;
import com.dkd.manage.domain.TbVendingMachine;
import com.dkd.manage.domain.vo.VmGetRegionEmp;
import com.dkd.manage.domain.vo.VmInfo2;
import com.dkd.manage.domain.vo.VmInfoWithChannelAndSku;
import com.dkd.manage.mapper.TbChannelMapper;
import com.dkd.manage.service.ITbVendingMachineService;
import com.dkd.manage.service.impl.TbChannelServiceImpl;
import com.dkd.manage.service.impl.TbEmpServiceImpl;
import com.dkd.manage.service.impl.TbSkuServiceImpl;
import com.dkd.manage.service.impl.TbVendingMachineServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import static com.dkd.framework.datasource.DynamicDataSourceContextHolder.log;
/**
 * 设备Controller
 *
 * @author ruoyi
 * @date 2024-11-23
 */
@RestController
@RequestMapping("/manage/vm")
public class TbVendingMachineController extends BaseController {
    @Autowired
    private ITbVendingMachineService tbVendingMachineService;
    @Autowired
    private TbChannelServiceImpl tbChannelServiceImpl;
    @Autowired
    private TbSkuServiceImpl tbSkuServiceImpl;
    @Autowired
    private TbEmpServiceImpl tbEmpServiceImpl;
    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbVendingMachine tbVendingMachine) {
        startPage();
        List<TbVendingMachine> list = tbVendingMachineService.selectTbVendingMachineList(tbVendingMachine);
        return getDataTable(list);
    }
    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbVendingMachine tbVendingMachine) {
        List<TbVendingMachine> list = tbVendingMachineService.selectTbVendingMachineList(tbVendingMachine);
        ExcelUtil<TbVendingMachine> util = new ExcelUtil<TbVendingMachine>(TbVendingMachine.class);
        util.exportExcel(response, list, "设备数据");
    }
    //查询设备详情
    @PreAuthorize("@ss.hasPermi('manage:vm:vmInfo')")
    @GetMapping("/vmInfo/{id}")
    public AjaxResult vmInfo(@PathVariable("id") Long id) {
        VmInfo2 vmInfo2 = tbVendingMachineService.selectVmInfoById(id);
        //vmInfo2转成json对象, 再把detail属性转成json对象，生成一个新的json对象，再返回前端
        String detail = vmInfo2.getDetail();
        //将detail字符串转成json数组
        List<JSONObject> listJson = JSON.parseArray(detail, JSONObject.class);
        JSONObject object = new JSONObject();
        //将vmInfo2对象属性复制到object对象中, 并把detail属性替换成listJson,忽略掉detail属性
        BeanUtil.copyProperties(vmInfo2, object, "detail");
        object.put("detail", listJson);
        return success(object);
    }
    //查询设备详情
    @PreAuthorize("@ss.hasPermi('manage:vm:vmInfo')")
    @GetMapping("/vmWithChannelAndSkuInfo/{id}")
    public AjaxResult selectVmWithChannelAndSkuInfo(@PathVariable("id") Long id) {
        VmInfoWithChannelAndSku vmInfoWithChannelAndSku = tbVendingMachineService.selectVmWithChannelAndSkuInfo(id);
        return success(vmInfoWithChannelAndSku);
    }
    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tbVendingMachineService.selectTbVendingMachineById(id));
    }
    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbVendingMachine tbVendingMachine) {
        return toAjax(tbVendingMachineService.insertTbVendingMachine(tbVendingMachine));
    }
    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbVendingMachine tbVendingMachine) {
        return toAjax(tbVendingMachineService.updateTbVendingMachine(tbVendingMachine));
    }
    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('manage:vm:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tbVendingMachineService.deleteTbVendingMachineByIds(ids));
    }
    //修改设备关联的货道以及商品，批量修改货道信息
    @PreAuthorize("@ss.hasPermi('manage:vm:editChannelAndSku')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping("/editVmInfoById")
    public AjaxResult editVmInfoById(@RequestBody JSONObject vmInfo2) {
        Integer result = 0;
        //打印日志，看看参数是什么，使用若依的日志框架
        log.info("vmInfo2:{}", vmInfo2);
        //获取detail属性
        List<JSONObject> detailList = vmInfo2.getJSONArray("detail").toJavaList(JSONObject.class);
        //创建一个集合，用来存储TbChannel对象
        ArrayList<TbChannel> tbChannels = new ArrayList<TbChannel>();
        //循环detailList，获取每个对象，然后创建一个TbChannel对象，设置属性，添加到集合中
        detailList.forEach(item -> {
            //获取商品名称
            TbSku tbSku = tbSkuServiceImpl.selectTbSkuBySkuName(item.getString("商品"));
            //获取商品id
            TbChannel tbChannel = tbChannelServiceImpl.selectTbChannelById((long) item.getInteger("channelId"));
            //如果商品不为空，则设置商品id
            if (tbSku != null) {
                //设置商品id
                Long skuId = tbSku.getSkuId();
                //设置商品id
                tbChannel.setSkuId(skuId);
            } else {
                //设置商品id
                tbChannel.setSkuId(0L);
            }
            //添加到集合中
            tbChannels.add(tbChannel);
        });
        //批量修改货道信息
        if (tbChannels.size() > 0) {
            //批量修改货道信息
            result = tbChannelServiceImpl.batchUpdateTbChannels(tbChannels);
        }
        //返回结果
        return toAjax(result);
    }
    //通过设备id，找设备，关联区域id，找该区域的人员
    @PreAuthorize("@ss.hasPermi('manage:vm:list')")
    @GetMapping("/searchByRegion/{id}")
    public AjaxResult searchByRegion(@PathVariable("id") Long id) {
        VmGetRegionEmp empWithVmRegion = tbVendingMachineService.getEmpWithVmRegion(id);
        // 处理 empWithVmRegion 如果需要
        return success(empWithVmRegion);
    }
    //通过设备区域id，搜索该区域下的运营管理人员
    @PreAuthorize("@ss.hasPermi('manage:vm:list')")
    @GetMapping("/searchEmpByRegionId/{id}")
    public AjaxResult searchEmpByRegionId(@PathVariable("id") Long id) {
        TbEmp emp = new TbEmp();
        emp.setRegionId(id);
        //通过区域id，搜索该区域下的运营管理人员
        List<TbEmp> tbEmps = tbEmpServiceImpl.selectTbEmpList(emp);
        //返回结果
        return success(tbEmps);
    }
}
